<template>
  <div class="home" ref="previewEl" :style="backgroundStyle">
    <div v-if="loading" class="loading-container">
      <el-spinner></el-spinner>
      <p>Loading...</p>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
import { getMap } from '../api'
import { ElMessage } from 'element-plus'

const backgroundStyle = ref({})
const loading = ref(true)

function fetchBackgroundImage() {
  loading.value = true
  getMap({}).then(res => {
    loading.value = false
    if (res.success) {
      backgroundStyle.value = {
        backgroundImage: `url(${res.image})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }
    } else {
      ElMessage.error('Failed to load background image')
    }
  })
}

onMounted(() => {
  window.addEventListener('resize', resizePreview)
  resizePreview()
  fetchBackgroundImage()
})


const previewEl = ref(null)

function resizePreview() {
  if (previewEl.value) {
    previewEl.value.style.width = previewEl.value.offsetHeight + 'px'
  }
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizePreview)
})
</script>

<style scoped>
.home {
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  position: relative;
}

.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #909399;
}
</style>
